package com.itheima.ydd.interceptor;

import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1、获取请求头
        String token = request.getHeader("x-token");
        String frontToken = request.getHeader("token");
        //2、使用工具类，判断token是否有效
        boolean verifyToken = JwtUtils.verifyToken(token);
        boolean verifyFrontToken = JwtUtils.verifyToken(frontToken);
        //3、如果token失效，返回状态码401，拦截
        if(!(verifyToken || verifyFrontToken)) {
            System.out.println("拦截请求------------------------>"+request.getRequestURL());
                response.setStatus(401);
                return false;
        }

        if(JwtUtils.verifyToken(token)){
            //解析token，获取id和手机号码，构造User对象，存入Threadlocal
            Claims claims = JwtUtils.getClaims(token);
            String id = (String) claims.get("userId");
            String roleId = (String) claims.get("roleId");

            SysUser user = new SysUser();
            user.setId(id);
            user.setRoleId(roleId);

            UserHolder.set(user);
        }else {
            //解析token，获取id和手机号码，构造User对象，存入Threadlocal
            Claims claims = JwtUtils.getClaims(frontToken);
            Integer id = (Integer) claims.get("userId");
            String mobile = (String) claims.get("mobile");

            YddUser yddUser = new YddUser();
            yddUser.setId(id);
            yddUser.setMobile(mobile);
            UserHolder.set(yddUser);
        }
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
